package com.jungle.base.interceptor;

import com.jungle.common.core.domain.model.LoginUser;
import com.jungle.common.helper.LoginHelper;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.resource.jdbc.spi.StatementInspector;
import org.springframework.stereotype.Component;

/**
 * 数据权限拦截
 */
@Slf4j
//@Component
public class JpaPermissionInterceptor implements StatementInspector/*extends EmptyInterceptor*/ {
    private static final long serialVersionUID = -4686975463539802701L;

    @Override
    public String inspect(String sql) {
        log.info("这里是 Jpa sql拦截器.");

        //查预警数据时只查出用户所在区县的
        if (sql.contains("from yj_yjsjb")) {
            LoginUser loginUser;
            try {
                loginUser = LoginHelper.getLoginUser();
            } catch (NullPointerException e) {
                log.warn(e.getMessage());
                return sql;
            }
            Long userId = loginUser.getUserId();
            String xzqhbm = loginUser.getAreaCode();
            if (sql.contains("where")) {
                sql = sql.substring(0, sql.indexOf("where") + "where".length()) +
                    " yzqhbm like '" + xzqhbm + "' and " +
                    sql.substring(sql.indexOf("where") + "where".length());
            } else {
                sql = sql.substring(0, sql.indexOf("yj_yjsjb") + "yj_yjsjb".length()) +
                    " where yzqhbm like '" + xzqhbm + "'" +
                    sql.substring(sql.indexOf("yj_yjsjb") + "yj_yjsjb".length());
            }
            log.info("当前用户id:{},所在区县：{},修改后的sql：{}", userId, xzqhbm, sql);
        }
        return sql;

//        User userVO = userMapper.selectById(BaseContext.getCurrentId());
//        if (null == userVO) {
//            log.info("无法获取到登录用户，数据权限不拦截{}", sql);
//            return sql;
//        }
//        //管理员
//        if (userVO==null) {
//            log.info("无法获取到登录用户，数据权限不拦截{}", sql);
//            return sql;
//        }
        /**
         * 进入拦截器select tbluserrol0_.id as id1_5_, tbluserrol0_.role_id as role_id2_5_,
         * tbluserrol0_.user_id as user_id3_5_
         * from tbl_user_role tbluserrol0_ where tbluserrol0_.user_id=28
         * 进入拦截器SELECT rf.function_id,f.function_name,f.level,f.functionurl,f.parent_function_id,f.id,f.ranks
         * FROM tbl_role_function
         * rf LEFT JOIN tbl_function f ON f.id=rf.function_id WHERE rf.role_id=? AND f.`level` IN(1,2) ORDER BY f.ranks ASC
         *
         * select * from table xx wehre a = (select xx from table where aa = aa)
         */
        //如果SQL有租户条件则不入侵
//        if (sql.indexOf("tenant_id") == -1) {
//            Pattern compile = Pattern.compile("\\swhere\\s", Pattern.CASE_INSENSITIVE);
//            Matcher matcher = compile.matcher(sql);
//            int lastStart = 0;
//            String tenantId = userVO.getTenantId();
//            StringBuilder builder = new StringBuilder(sql);
//            while (matcher.find(lastStart)) {
//                String sqlTemp = builder.substring(lastStart, matcher.end());
//                String tableAs = getTableAs(sqlTemp);
//                String text = String.format("%stenant_id = '%s' and ", tableAs, tenantId);
//                builder.insert(matcher.end(), text);
//                lastStart = matcher.end() + text.length();
//                matcher = compile.matcher(builder.toString());
//            }
//            //没有where
//            if (lastStart == 0) {
//                String tableAs = getTableAs(sql);
//                builder.append(String.format("%stenant_id = '%s'", tableAs, tenantId));
//            }
//            sql = builder.toString();
//        }

    }


}

